//
//  Bundle+QCropper.swift
//  Aware
//
//  Created by Kevin on 2025/2/25.
//

import Foundation
import QCropper

extension Bundle {
    static var qc_refreshBundle: Bundle? {
        var bundle: Bundle?
        if bundle == nil {
            #if SWIFT_PACKAGE
            let containerBundle = SWIFTPM_MODULE_BUNDLE
            #else
            let containerBundle = Bundle(for: CropperViewController.self)
            #endif
            bundle = Bundle(path: containerBundle.path(forResource: "QCropper", ofType: "bundle") ?? "")
        }
        return bundle
    }
}

extension Bundle {
    static var qc_defaultI18nBundle: Bundle?
    static var qc_systemI18nBundle: Bundle?

    static func qc_localizedString(forKey key: String, value: String? = nil) -> String {
        var language =  Locale.preferredLanguages.first
        var bundle = Bundle.main
        
        let i18nFolderPath = bundle.path(forResource: language, ofType: "lproj")
        qc_defaultI18nBundle = Bundle(path: i18nFolderPath ?? "") ?? Bundle.main
        
        if qc_systemI18nBundle == nil {
            qc_systemI18nBundle = qc_defaultI18nBundle(withLanguage: language ?? "en")
        }
        
        var localizedString = qc_systemI18nBundle?.localizedString(forKey: key, value: value, table: nil) ?? value
        localizedString = qc_defaultI18nBundle?.localizedString(forKey: key, value: localizedString, table: nil) ?? localizedString
        return localizedString ?? ""
    }

    static func qc_defaultI18nBundle(withLanguage language: String) -> Bundle {
        var language = language
        if language.hasPrefix("zh") {
            if language.contains("Hans") {
                language = "zh-Hans" // 简体中文
            }
        } else {
            language = "en"
        }
        
        return Bundle(path: qc_refreshBundle?.path(forResource: language, ofType: "lproj") ?? "") ?? Bundle.main
    }
}
